const _ = require('lodash');
const async = require('async');
const commonService = require('../common');

function getList(params, callback) {
  const { SysDictionary: dictionaryModel } = commonService.getModels();
  const pageNumber = _.toNumber(params.pageNumber);
  const pageSize = _.toNumber(params.pageSize);
  const Keywords = !_.isEmpty(params.Keywords) ? params.Keywords : '';
  if (params.isSuperUser === 'true') {
    const filter = {
      limit: pageSize,
      skip: pageSize * (pageNumber - 1),
    };

    commonService.getList(dictionaryModel, filter, callback);
  } else if (!_.isEmpty(params.userFormIds)) {
    let sql = `SELECT * FROM elanco_sys.sys_dictionary 
                 WHERE sys_deleted = false `;
    Keywords ? sql += `AND name like '%${Keywords}%' ` : '';
    sql += ` AND (SELECT ARRAY(SELECT (jsonb_array_elements_text(others->'formIds'))::int) && ARRAY[${params.userFormIds}])
                       ORDER BY id OFFSET ${pageSize * (pageNumber - 1)} LIMIT ${pageSize};`;
    commonService.executeSql(sql, [], {}, callback);
  } else {
    callback(null, []);
  }
}

function getPageTotal(params, callback) {
  const { SysDictionary: dictionaryModel } = commonService.getModels();
  const pageSize = _.toNumber(params.pageSize);
  const Keywords = !_.isEmpty(params.Keywords) ? params.Keywords : '';
  if (params.isSuperUser === 'true') {
    commonService.getCount(dictionaryModel, (error, count) => callback(error, _.ceil(count / pageSize)));
  } else if (!_.isEmpty(params.userFormIds)) {
    const getListCount = (next) => {
      let sql = `SELECT COUNT(id) FROM elanco_sys.sys_dictionary 
                   WHERE (SELECT ARRAY(SELECT (jsonb_array_elements_text(others->'formIds'))::int) && ARRAY[${params.userFormIds}]) `;
      Keywords ? sql += `AND name like '%${Keywords}%' ` : '';
      sql += ' AND sys_deleted = false;';
      commonService.executeSql(sql, [], {}, next);
    };
    async.waterfall([getListCount], (error, data) => {
      callback(error, _.ceil(_.toNumber(data[0].count) / _.toNumber(params.pageSize)));
    });
  } else {
    callback(null, 0);
  }
}

function getAllEnableForms(params, callback) {
  const { WfForm: formModel } = commonService.getModels();
  commonService.getList(formModel, { where: { status: 1 } }, callback);
}

module.exports = {
  getList,
  getPageTotal,
  getAllEnableForms,
};
